package com.instalinks.android.smspostservice;

import java.util.Hashtable;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.instalinks.android.lib.UrlData;
import com.instalinks.android.lib.UrlResponse.UrlResponseType;
import com.instalinks.android.smspostservice.activity.HomeActivity;
import com.instalinks.android.smspostservice.utils.AppConfig;
import com.instalinks.android.smspostservice.utils.Constants;
import com.instalinks.android.smspostservice.utils.enums.ConfigParams;
import com.instalinks.android.smspostservice.utils.enums.PhoneParams;

public class RegistrationActivity extends Activity {

	private EditText txtSubscriberID;
	private EditText txtEmail;
	private EditText txtPassword;
	private EditText txtConfirmPassword;
	private Button btnRegister;

	private AppConfig mAppCfg;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		mAppCfg = new AppConfig(this);

		initialize();
	}

	@Override
	public void onBackPressed() {
		this.finish();
	}

	private boolean isAlreadyRegistred() {

		if(mAppCfg.getEmail().length()<0)
			return false;
		
		boolean result = mAppCfg.updateConfigFromHost();

		if (result) {
			if (mAppCfg.isSubscribedFlag())
				return true;
			else
				return false;
		} else {
			mAppCfg.alert(getString(R.string.network_error));
			finish();
		}
		return false;
	}

	private void initialize() {
		String email = mAppCfg.getEmail();
//		email = ""; // FOR TESTING
		if(email.length()==0){
			jumpToError(Constants.ERR_NOEMAIL);
			return;
		}else if (mAppCfg.getEmail().length()>0 && isAlreadyRegistred()) {
			jumpToHome();
			return;
		}

		this.setContentView(R.layout.registration);

		txtSubscriberID = (EditText) findViewById(R.id.txtSubscriberID);
		txtEmail = (EditText) findViewById(R.id.txtEmail);
		txtPassword = (EditText) findViewById(R.id.txtPassword);
		txtConfirmPassword = (EditText) findViewById(R.id.txtConfirmPassword);
		btnRegister = (Button) findViewById(R.id.btnRegister);

		txtSubscriberID.setText(mAppCfg.getSubscriberId());
		txtEmail.setText(mAppCfg.getEmail());

		btnRegister.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				registerUser();
			}
		});
	}

	private void jumpToError(String error) {
		Intent i = new Intent();
		i.setClassName(getApplicationContext().getPackageName(),
				ErrorActivity.class.getName());
		
		Bundle bundle = new Bundle();
		bundle.putString("error", error);
		i.putExtras(bundle);
		
		startActivity(i);
		this.finish();
	}

	private void jumpToHome() {
		this.finish();

		Intent i = new Intent();
		i.setClassName(getApplicationContext().getPackageName(),
				HomeActivity.class.getName());
		startActivity(i);
	}

	private void registerUser() {

		if (mAppCfg.isConnectedToNetwork()) {
			String pwd = txtPassword.getText().toString();
			String cpwd = txtConfirmPassword.getText().toString();

			if (!pwd.equals(cpwd)) {
				mAppCfg.alert("Password and Confirm Password do not match");
				return;
			}

			mAppCfg.rePopulate();

			String deviceId = mAppCfg.getDeviceId();
			String subscriberId = txtSubscriberID.getText().toString();
			String email = txtEmail.getText().toString();
			String password = txtPassword.getText().toString();
			String urlS = mAppCfg.getDataPostUrl();

			RegisterTask task = new RegisterTask();
			task.execute(deviceId, subscriberId, email, password, urlS);
		} else {
			mAppCfg.alert(getString(R.string.network_error));
		}
	}

	private void registrationSucceeded() {
		boolean result = mAppCfg.updateConfigFromHost();

		if (result) {
			this.finish();

			Intent i = new Intent();
			i.setClassName(getApplicationContext().getPackageName(),
					HomeActivity.class.getName());
			startActivity(i);
		} else {
			mAppCfg.alert("Unable to load the new config post registration. Try reopening the application.");
		}
	}

	private void registrationFailed(String msg) {
		mAppCfg.alert(msg);
	}

	private class RegisterTask extends AsyncTask<String, Void, Boolean> {

		private ProgressDialog pd;
		private String message;

		@Override
		protected void onPreExecute() {
			pd = ProgressDialog.show(RegistrationActivity.this, "",
					"Registration in progress...");
		}

		@Override
		protected Boolean doInBackground(String... params) {
			message = "";

			String deviceId = params[0];
			String subId = params[1];
			String email = params[2];
			String password = params[3];
			String urlS = params[4];

			com.instalinks.android.lib.UrlData urlData = new UrlData(urlS);
			Hashtable<String, String> htParams = new Hashtable<String, String>();
			htParams.put(ConfigParams.mode.toString(),
					ConfigParams.modes.signup.toString());
			htParams.put(PhoneParams.deviceid.toString(), deviceId);
			htParams.put(PhoneParams.subid.toString(), subId);
			htParams.put(PhoneParams.email.toString(), email);
			htParams.put(PhoneParams.password.toString(), password);

			com.instalinks.android.lib.UrlResponse response = urlData
					.postData(htParams);

			this.message = response.getMessage();
			boolean result = (response.getResponseType() == UrlResponseType.success);
			return result;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			pd.dismiss();
			pd.cancel();

			if (result && message.toLowerCase().startsWith("error")) {
				registrationFailed(message);
			} else {
				registrationSucceeded();
			}
		}
	}
}
